package com.distribute.framework.core.xwork;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("unchecked")
public class WebContext
{
	static ThreadLocal webContext = new ThreadLocal();
	
	public static final String XWORK_REQUEST = "com.distribute.framework.core.xwork.WebContext.request";
	
	public static final String XWORK_RESPONSE = "com.distribute.framework.core.xwork.WebContext.response";

	private static final String XWORK_SESSION = "com.distribute.framework.core.xwork.WebContext.session";

	private static final String XWORK_PARAMETERS = "com.distribute.framework.core.xwork.WebContext.parameters";
	
	private static final String XWORK_SERVLETCONTEXT = "com.distribute.framework.core.xwork.WebContext.parameters";
		
	public WebContext()
	{
		
	}

	public static Map<String, Object> getContext()
	{
		Map<String, Object> context = (Map<String, Object>) webContext.get();
		if(context==null)
		{
			context=new HashMap();
			webContext.set(context);
		}
		return context;
	}
	
	public static ServletContext getServletContext()
	{
		return (ServletContext) getContext().get(XWORK_SERVLETCONTEXT);
	}
	
	public static void setServletContext(ServletContext servletContext) {
		getContext().put(XWORK_SERVLETCONTEXT, servletContext);
	}
	
	public static HttpServletRequest getServletRequest()
	{
		return (HttpServletRequest) getContext().get(XWORK_REQUEST);
	}
	
	public static void setServletRequest(HttpServletRequest request)
	{
		getContext().put(XWORK_REQUEST, request);
	}
	
	public static HttpSession getHttpSession()
	{
		return (HttpSession) getContext().get(XWORK_SESSION);
	}
	
	public static void setHttpSession(HttpSession session)
	{
		getContext().put(XWORK_SESSION, session);
	}
	
	public void setParameters(Map<String, Object> parameters)
	{
		getContext().put(XWORK_PARAMETERS,parameters);
	}
	
	public Map<String, Object> getParameters()
	{
		return (Map<String, Object>) getContext().get(XWORK_PARAMETERS);
	}

	public static HttpServletResponse getServletResponse()
	{
		return (HttpServletResponse) getContext().get(XWORK_RESPONSE);
	}
	
	public static void setServletResponse(HttpServletResponse response)
	{
		getContext().put(XWORK_RESPONSE, response);
	}
	
	public static void removeAttribute(String key){
		getContext().remove(key);
	}
	
	public static void setAttribute(String key,Object value){
		getContext().put(key, value);
	}
	
	public static <T> T getAttribute(String key){
		
		return (T) getContext().get(key);
	}
}